<template>
  <tn-scroll-list :indicator="false">
    <view class="items">
      <!-- 有订单数据时显示订单列表 -->
      <template v-if="projectList.length > 0">
        <view v-for="item in projectList" :key="item.id" class="item" @tap="goDetail(item.id)">
          <view class="row">
            <text class="title">{{ item.title }}</text>
            <text class="totalPrice">{{ item.totalPrice }}元</text>
          </view>
          <view class="row">
            <view class="tags">
              <tn-tag
                v-for="text in Object.values(item.categorySelectionMap)"
                :key="text"
                width="128rpx"
                height="44rpx"
                shape="circle"
                backgroundColor="rgba(75, 123, 245, 0.1)"
                fontColor="#4B7BF5"
                fontSize="24"
              >
                {{ text }}
              </tn-tag>
            </view>
            <tn-tag  :backgroundColor="`tn-bg-${item.orderPayStatusOption.bgColor}--light`"
              :fontColor="`tn-color-${item.orderPayStatusOption.color}`" 
										height="48rpx" width="100">
										{{ item.orderPayStatusOption.text }}
									</tn-tag>
          </view>
          <view class="row">
            <text class="description">
              描述：{{ formatDescText(item.requirementDescription) }}
            </text>
          </view>
          <view class="row">
            <text class="expectedDeliveryTime">
              期望交付周期：{{ item.expectedDeliveryTime }}
            </text>
            <view class="action-buttons">
              <!-- 修改订单按钮 - 只在待付定金状态下显示 -->
              <tn-button
                v-if="item.orderPayStatus === 1"
                class="action edit-button"
                padding="6rpx 9rpx"
                shape="round"
                backgroundColor="#4B7BF5"
                fontSize="24"
                fontColor="#FFFFFF"
                width="132rpx"
                height="48rpx"
                @tap.stop="goEdit(item.id)"
              >
                修改订单
              </tn-button>
              <!-- 立即付款按钮 - 只在待付定金或尾款待支付状态下显示 -->
              <tn-button
                v-if="item.orderPayStatus === 1 || item.orderPayStatus === 4"
                class="action pay-button"
                padding="6rpx 9rpx"
                shape="round"
                backgroundColor="#FF6B35"
                fontSize="24"
                fontColor="#FFFFFF"
                width="132rpx"
                height="48rpx"
                @tap.stop="goDetail(item.id)"
              >
                立即付款
              </tn-button>
            </view>
          </view>
        </view>
      </template>
      
      <!-- 没有订单数据时显示占位符 -->
      <view v-else class="empty-placeholder">
        <image 
          class="empty-image" 
          src="https://lemawuyou.oss-cn-shanghai.aliyuncs.com/client/images/empty/data.jpg"
          mode="aspectFit"
        ></image>
        <text class="empty-text">暂无待处理订单数据</text>
        <text class="empty-desc">您还没有需要处理的订单</text>
      </view>
    </view>
  </tn-scroll-list>
</template>

<script>
import { getProjectList } from "@/api/project";
import staticDict from "@/util/staticDict";
import { to } from "@/util/request";

export default {
  name: "Orders",
  props: {
    isShow: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    isLoggedIn() {
      try {
        return !!uni.getStorageSync('userInfo')
      } catch (e) {
        return false
      }
    }
  },
  data() {
    return {
      projectList: [],
      navigating: false,
    };
  },
  methods: {
    // 将 Markdown 清洗为简洁的单行文本，适用于列表摘要
    formatDescText(md = '') {
      if (!md) return ''
      return md
        // 去除代码块/行内代码
        .replace(/```[\s\S]*?```/g, ' ')
        .replace(/`[^`]*`/g, ' ')
        // 去除链接 [text](url) 和 <url>
        .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1')
        .replace(/<([^>]+)>/g, '$1')
        // 去除标题/列表标记
        .replace(/^#{1,6}\s*/gm, '')
        .replace(/^\s*[-*+]\s+/gm, '')
        .replace(/^\s*\d+\.\s+/gm, '')
        // 去除多余的 ** * _ ~ 等格式符
        .replace(/[\*#_~>]/g, '')
        // 压缩空白与换行
        .replace(/\s+/g, ' ')
        .trim()
    },
    navigateOnce(url){
      if (this.navigating) return;
      this.navigating = true;
      uni.navigateTo({
        url,
        complete: () => {
          // 兜底延时，避免某些端 complete 过早导致再次触发
          setTimeout(() => { this.navigating = false }, 300);
        }
      })
    },
    goDetail(id){
      this.navigateOnce(`/homepages/detail?id=${id}`)
    },
    goEdit(id){
      this.navigateOnce(`/discoverypages/order?mode=update&id=${id}`)
    },
    async getOrders() {
      // 未登录直接返回，避免请求接口
      if (!this.isLoggedIn) {
        this.projectList = []
        return
      }
      const [err, res] = await to(getProjectList());
      if (err) {
        uni.showToast({
          icon: "error",
          title: "查询订单失败",
        });
        return;
      }
      const orderStatusOptions = staticDict.orderStatus;
      this.projectList = (res.data ?? [])
        .filter(item => item.orderPayStatus === 1 || item.orderPayStatus === 4)
        .map((item) => ({
          ...item,
          totalPrice: item.totalPrice ?? 0,
          orderPayStatusOption:
            orderStatusOptions[item.orderPayStatus] ?? orderStatusOptions[1],
        }));
    },
  },
  watch: {
    isShow(newVal, oldVal) {
      if (newVal && this.isLoggedIn) {
        this.getOrders();
      }
    },
  },
  mounted() {
    if (this.isLoggedIn) {
      this.getOrders();
    }
  },
};
</script>

<style lang="scss" scoped>
.items {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
  width: 100%;
}

.item {
  display: flex;
  flex-direction: column;
  gap: 18rpx;
  padding: 32rpx;
  border-radius: 24rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 4rpx 0 rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2rpx);
    box-shadow: 0 4rpx 12rpx 0 rgba(0, 0, 0, 0.1);
  }

  .row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16rpx;
  }

  .row:first-of-type {
    margin-top: 6rpx;
  }

  .row > view:first-child,
  .row > text:first-child {
    width: 490rpx;
  }

  .title {
    font-size: 32rpx;
    font-weight: 500;
    line-height: 48rpx;
    color: #000;
  }

  .totalPrice {
    font-size: 32rpx;
    font-weight: 500;
    line-height: 48rpx;
    white-space: nowrap;
    color: #4b7bf5;
  }

  .tags {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
  }

  .description {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 24rpx;
    font-weight: normal;
    line-height: 36rpx;
    color: #666666;
  }

  .expectedDeliveryTime {
    font-size: 24rpx;
    font-weight: normal;
    line-height: 36rpx;
    color: #999999;
  }

  .action-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 16rpx;
    align-items: center;
  }

  .pay-button {
    margin-right: 0;
  }
  
  .edit-button {
    margin-left: 0;
  }
}

.empty-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx 32rpx;
  border-radius: 24rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 4rpx 0 rgba(0, 0, 0, 0.05);
  min-height: 300rpx;
  flex: 1;
  min-width: 100%;
  width: calc(100vw - 48rpx);

  .empty-image {
    width: 100%;
    height: 100rpx;
    margin-bottom: 32rpx;
  }

  .empty-text {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
    margin-bottom: 16rpx;
  }

  .empty-desc {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 40rpx;
  }
}
</style>